package cn.com.fuhuitong.main.goods.popup

import android.annotation.SuppressLint
import android.content.Context
import android.view.*
import android.view.animation.Animation
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import cn.com.fuhuitong.app.BASE_HTTP_URL
import cn.com.fuhuitong.main.base.RecyclerViewHolder
import cn.com.fuhuitong.main.goods.entity.GoodsDetailsEntity
import cn.com.fuhuitong.main.goods.entity.GoodsSpecsEntity
import com.bumptech.glide.Glide
import cn.com.fuhuitong.R
import cn.com.fuhuitong.app.getImageUrl
import cn.com.fuhuitong.main.goods.ui.activity.GoodsDetailsActivity.Action
import cn.com.fuhuitong.utils.SpanUtils
import cn.com.fuhuitong.utils.ToastUtils
import kotlinx.android.synthetic.main.item_goods_details_specs.view.*
import kotlinx.android.synthetic.main.popup_goods_details_specs.view.*
import razerdp.basepopup.BasePopupWindow


class GoodsSpecsPopupWindow(
    context: Context, val isMember: Boolean = false,
    val action: (action: Action, specsEntity: GoodsSpecsEntity) -> Unit
) : BasePopupWindow(context) {

    private lateinit var specsEntity: GoodsSpecsEntity

    init {
        popupGravity = Gravity.BOTTOM
        setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING)
        setAutoShowInputMethod(false)
    }

    override fun onCreateContentView(): View {
        return createPopupById(R.layout.popup_goods_details_specs)
    }

    override fun onViewCreated(contentView: View) {
        super.onViewCreated(contentView)
        contentView.text_goods_details_close
            .setOnClickListener { dismiss() }

        //加入购物车
        contentView.text_goods_details_add_cart.setOnClickListener {
            action(Action.ADD_CART, specsEntity)
            this.dismiss()
        }
        //立即购买
        contentView.text_goods_details_buy_now.setOnClickListener {
            action(Action.BUY_NOW, specsEntity)
            this.dismiss()
        }
        //确认
        contentView.text_goods_details_confirm.setOnClickListener {
            action(Action.SPECS, specsEntity)
            this.dismiss()
        }

        //数量加
        contentView.text_goods_details_plus.setOnClickListener {
            if (detailsEntity.stock == 0) {
                ToastUtils.showShort(context, "库存不足")
                return@setOnClickListener
            }
            specsEntity.count += 1
            if (specsEntity.count > specsEntity.specifications_num) {
                specsEntity.count = specsEntity.specifications_num
                ToastUtils.showShort(context, "不能超过库存哦")
            }
            contentView.text_goods_details_count.text =
                specsEntity.count.toString()
            contentView.text_goods_details_number.text =
                specsEntity.count.toString()
        }
        //数量减
        contentView.text_goods_details_reduce.setOnClickListener {
            if (detailsEntity.stock == 0) {
                ToastUtils.showShort(context, "库存不足")
                return@setOnClickListener
            }
            specsEntity.count -= 1
            if (specsEntity.count == 0) {
                specsEntity.count = 1
                ToastUtils.showShort(context, "商品数据至少为1")
            } else {
                if (specsEntity.count > specsEntity.specifications_num) {
                    specsEntity.count = specsEntity.specifications_num
                    ToastUtils.showShort(context, "不能超过库存哦")
                }
                contentView.text_goods_details_count.text =
                    specsEntity.count.toString()
                contentView.text_goods_details_number.text =
                    specsEntity.count.toString()
            }
        }
    }

    override fun onCreateShowAnimation(width: Int, height: Int): Animation {
        return getTranslateVerticalAnimation(1F, 0F, 400)
    }

    override fun onCreateDismissAnimation(): Animation {
        return getTranslateVerticalAnimation(0F, 1F, 400)
    }

    private lateinit var detailsEntity: GoodsDetailsEntity

    /**
     * 初始化数据
     * */
    fun initDataPopupWindow(
        action: Action, detailsEntity: GoodsDetailsEntity,
        specsEntity: MutableList<GoodsSpecsEntity> = mutableListOf()
    ) {
        this.detailsEntity = detailsEntity
        contentView.linear_goods_details_specs.visibility =
            if (specsEntity.size == 0) View.GONE else View.VISIBLE
        contentView.text_goods_details_add_cart.visibility =
            if (isMember) View.GONE else View.VISIBLE
        contentView.text_goods_details_buy_now.text =
            if (isMember) "立即预约" else "立即购买"
//        contentView.linear_goods_details_add_buy.visibility =
//            if (action == Action.SPECS) View.GONE else View.VISIBLE
//        contentView.text_goods_details_confirm.visibility =
//            if (action == Action.SPECS) View.VISIBLE else View.GONE

        if (specsEntity.size == 0) {
            this.specsEntity = detailsEntity.specifications ?: GoodsSpecsEntity(
                member_discount = detailsEntity.member_discount,
                member_discount_price = detailsEntity.member_discount_price,
                specifications_name = "",
                specifications_num = detailsEntity.stock,
                specifications_price = detailsEntity.price
            )
            this.specsEntity.count = if (detailsEntity.stock == 0) 0 else 1
            this.initAttribute(
                detailsEntity.banner_images, this.specsEntity
            )
        } else {
            val layoutManager = GridLayoutManager(context, 4)
            with(contentView.recycler_goods_details_specs) {
                this.layoutManager = layoutManager
            }
            val specsLabelAdapter: GoodsSpecsLabelAdapter =
                GoodsSpecsLabelAdapter(context, specsEntity).apply {
                    val goodsSpecsEntity: GoodsSpecsEntity? = detailsEntity.specifications
                    if (goodsSpecsEntity == null) {
                        this@GoodsSpecsPopupWindow.specsEntity = specsEntity[selectedPosition]
                        this@GoodsSpecsPopupWindow.specsEntity.count = 1
                    } else for ((index: Int, item: GoodsSpecsEntity) in this.specsEntity.withIndex())
                        if (item.id == goodsSpecsEntity.id) {
                            this.selectedPosition = index
                            item.count = if (goodsSpecsEntity.count == 0)
                                1 else goodsSpecsEntity.count
                            this@GoodsSpecsPopupWindow.specsEntity = item
                            break
                        }
                    this@GoodsSpecsPopupWindow.initAttribute(
                        detailsEntity.banner_images,
                        this@GoodsSpecsPopupWindow.specsEntity
                    )
                }
            contentView.recycler_goods_details_specs.adapter = specsLabelAdapter
            specsLabelAdapter.setOnItemClickListener { _, _, entity ->
                entity.count = if (this@GoodsSpecsPopupWindow.specsEntity.count == 0)
                    1 else this@GoodsSpecsPopupWindow.specsEntity.count
                this@GoodsSpecsPopupWindow.specsEntity = entity
                this.initAttribute(detailsEntity.banner_images, this.specsEntity)
            }
        }

    }


    @SuppressLint("SetTextI18n")
    fun initAttribute(image: String, entity: GoodsSpecsEntity) {
        Glide.with(contentView).load(getImageUrl(image.split(",")[0]))
            .into(contentView.image_goods_details_icon)
        contentView.text_goods_details_price.text =
            SpanUtils.setMoneyStyle(entity.specifications_price.toDouble())
        contentView.text_goods_details_stock.text =
            "库存：${entity.specifications_num}"
        contentView.text_goods_details_specs.text =
            "已选择：${entity.specifications_name}${if (entity.specifications_name.isEmpty()) "" else "，"}"
        contentView.text_goods_details_count.text =
            entity.count.toString()
        contentView.text_goods_details_number.text =
            entity.count.toString()
    }

    class GoodsSpecsLabelAdapter(
        private val mContext: Context, val specsEntity: MutableList<GoodsSpecsEntity>
    ) : RecyclerView.Adapter<RecyclerViewHolder>() {

        var selectedPosition = 0
            set(value) {
                if (field != value) {
                    field = value
                    notifyDataSetChanged()
                }
            }

        private var onItemClickListener: ((View, Int, GoodsSpecsEntity) -> Unit)? = null

        fun setOnItemClickListener(onItemClickListener: ((View, Int, GoodsSpecsEntity) -> Unit)) {
            this.onItemClickListener = onItemClickListener
        }

        override fun onCreateViewHolder(
            parent: ViewGroup, viewType: Int
        ): RecyclerViewHolder {
            return RecyclerViewHolder(
                LayoutInflater.from(mContext)
                    .inflate(R.layout.item_goods_details_specs, parent, (false))
            )
        }

        override fun getItemCount(): Int {
            return specsEntity.size
        }

        override fun onBindViewHolder(holder: RecyclerViewHolder, position: Int) {
            val itemView: View = holder.itemView
            itemView.text_goods_details_specs_item.text =
                specsEntity[position].specifications_name
            with(itemView.text_goods_details_specs_item) {
                text = specsEntity[position].specifications_name
            }

            holder.itemView.isSelected = holder.layoutPosition == selectedPosition

            holder.itemView.setOnClickListener {
                selectedPosition = position
                onItemClickListener?.invoke(it, position, specsEntity[position])
            }
        }

    }

}